package com.xxwy.ddu.security.browser.impl;

import com.xxwy.ddu.security.code.vaildatecode.ValidateCode;
import com.xxwy.ddu.security.code.vaildatecode.ValidateCodeRepository;
import com.xxwy.ddu.security.code.vaildatecode.ValidateCodeType;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

/**
 * @author xxwy
 * on 2018/8/29 0029
 * 把验证码存放待session中
 */
@Component("validateCodeRepository")
public class BrowserValidateCodeRepository implements ValidateCodeRepository {

    /**
     * 前缀
     */
    String SESSION_KEY_PREFIX = "SESSION_KEY_FOR_CODE_";

    /**
     * 操作session的工具类
     */
    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    @Override
    public void save(ServletWebRequest request, ValidateCode code, ValidateCodeType type) {
        sessionStrategy.setAttribute(request,getSessionKey(request,type),code);
    }

    @Override
    public ValidateCode get(ServletWebRequest request, ValidateCodeType type) {
        return (ValidateCode) sessionStrategy.getAttribute(request, getSessionKey(request, type));
    }

    @Override
    public void remove(ServletWebRequest request, ValidateCodeType type) {
        sessionStrategy.removeAttribute(request,getSessionKey(request,type));
    }

    /**
     * 构建验证码放入session时的key
     *
     * @param request
     * @return
     */
    private String getSessionKey(ServletWebRequest request , ValidateCodeType type) {
        return SESSION_KEY_PREFIX + type.toString().toUpperCase();
    }


}
